var CometPipe = (function(){
    
    var _defConfig = {
        initAjaxType : 'get',
        api : '/events'
    };
    
    var CometPipe = function(config){
        var _this = this;
        Observable.enable(this);
        this.config = $.extend(true, {}, _defConfig, config);
        this.requestCount = 0;
        this.timeout = 1.5 * 60 * 1000;
        this.allowRestart = true;   //是否允许重新连接.
        
        this.lastResponseTick = 0;
        this.detectAliveTimer = new ujs.Timer({
            timerFun : function(){            
                if(!_this.detectAlive()){
                    var $reconnect = $('<span>Disconnected from server.<a class="reconnect" href="#">Reconnect</a></span>');
                    $reconnect.find('a').click(function(){
                        _this.start();
                        return false;
                    });
                    page.errorPanel.show().setContent($reconnect);
                }
            },
            interval : 1000 * 0.2 * 60
        }); 
               
        (function(){
            _this.detectAliveTimer.start();    
        }).defer(5000);   
             
        this._init();
    };    
    CometPipe.prototype._init = function(){
        this.ajaxType = this.config['initAjaxType'];
        this.api = this.config['api'];
    };    
    CometPipe.prototype.request = function(data){
        var _this = this,
            requestPromise = null;
            
        this.api = ujs.browser.loc.addQuery(this.api, {           
            n : _this.requestCount++
        });
        
        if(page.cid){
            this.api = ujs.browser.loc.addQuery(this.api, {
                cid : page.cid
            });
        }
                
        if(!Type.isUndefined(data)){
            _this.ajaxType = 'post';            
            requestPromise = $.ajax({
                type : 'post',
                url : _this.api,
                data : data,
                timeout : _this.timeout
            });
        } else {
            _this.ajaxType = 'get';
            requestPromise = $.ajax({
                url : _this.api,
                timeout : _this.timeout
            }); 
        }
        this.requestPromise = requestPromise;
        requestPromise.done(ujs.hr(
            function(msg){
                //成功响应.
                _this.lastResponseTick = Date.now();
                page.errorPanel.hide();
                page.findAuth.end();
                try {
                    _this.fire('response', msg);
                } catch(e){
                    console.log(e);  
                    ujs.util.debug.error(e);  
                    _this.restartLater(1000);
                }
            },
            function(msg){
                _this.lastResponseTick = Date.now();
                page.errorPanel.hide();                
                //服务器自定义错误.
                try {
                    _this.fire('error', msg);
                } catch(e){
                    ujs.util.debug.error(e);  
                    console.log(e);
                }                
                _this.restartLater(1000);
            })
        ).fail(function(response){
            _this.lastResponseTick = Date.now();
            //网络错误，其它错误。
            try {
                page.errorPanel.show().setContent('Disconnected from server.');
                if(response){
                    _this.fire('error', {
                        code : response.status
                    });
                }
            } catch(e){
                console.log(e);
                ujs.util.debug.error(e);  
            }            
            _this.restartLater();
        }); 
    };
    CometPipe.prototype.start = function(){
        this.request();
    };
    CometPipe.prototype.restart = function(){
        if(this.allowRestart){
            page.errorPanel.hide();
            // page.errorPanel.show().setContent('Reconnecting ...');
            this._init();
            this.request();
        }
    };    
    /**
     * 中断通道. 
     */    
    CometPipe.prototype.end = function(){
        this.allowRestart = false;
        this.detectAliveTimer.end();
        if(this.requestPromise && this.requestPromise.abort){
            this.requestPromise.abort();
        } 
        window.clearTimeout(this.restartTaskPtr);        
    };    
    CometPipe.prototype.detectAlive = function(){
        return (Date.now() - this.lastResponseTick) < 1000 * 60 * 3.0;   
    };    
    CometPipe.prototype.restartLater = function(ms){        
        ms = ms || 5000;
        this.requestCount = 0;
        this.restartTaskPtr = this.restart.defer(ms, this);
        console.log('restart pipe {0}ms later.'.format(ms));
    };
    
    return CometPipe;
})();